import React, { useEffect, useState } from "react";
import { Card, Typography, Space, Row, Col, Tag, Button, Input } from "antd";
import { useNavigate } from "react-router-dom";
import { SearchOutlined } from "@ant-design/icons";
import exampleRoutes from "../../router/routes/exampleRoutes";
import { RouteConfig } from "../../router/types";
import Icon from "../../utils/icons";
import styles from "./ExampleIndex.module.less";

const { Title, Paragraph } = Typography;

interface ExampleCardProps {
  example: RouteConfig;
  onClick: () => void;
}

// 示例卡片组件
const ExampleCard: React.FC<ExampleCardProps> = ({ example, onClick }) => {
  const iconName =
    typeof example.meta?.icon === "string" ? example.meta?.icon : "Example";
  const title = example.meta?.title || "未命名示例";

  return (
    <Card className={styles.exampleCard} hoverable onClick={onClick}>
      <div className={styles.cardContent}>
        <div className={styles.iconWrapper}>
          {iconName.startsWith("http") ? (
            <img src={iconName} alt={title} className={styles.cardIcon} />
          ) : (
            <div className={styles.iconContainer}>
              {typeof iconName === "string" && iconName.startsWith("�") ? (
                <span className={styles.emoji}>{iconName}</span>
              ) : (
                <Icon
                  name={typeof iconName === "string" ? iconName : "Example"}
                  size={32}
                />
              )}
            </div>
          )}
        </div>
        <div className={styles.cardTitle}>{title}</div>
        <div className={styles.cardPath}>
          <Tag color="blue">{`/${example.path}`}</Tag>
        </div>
      </div>
    </Card>
  );
};

const ExampleIndex: React.FC = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("所有示例");
  const [filteredExamples, setFilteredExamples] =
    useState<RouteConfig[]>(exampleRoutes);

  // 定义分类规则
  const categoryFilters = {
    所有示例: () => true, // 全部展示
    UI组件: (e: RouteConfig) =>
      e.path?.includes("demo") || e.meta?.title?.includes("组件"),
    工具函数: (e: RouteConfig) =>
      e.path?.includes("util") || e.path?.includes("string"),
    数据处理: (e: RouteConfig) =>
      e.path?.includes("data") || e.path?.includes("api"),
  };

  // 计算示例分类
  const categories = [
    { title: "所有示例", count: exampleRoutes.length },
    {
      title: "UI组件",
      count: exampleRoutes.filter(categoryFilters["UI组件"]).length,
    },
    {
      title: "工具函数",
      count: exampleRoutes.filter(categoryFilters["工具函数"]).length,
    },
    {
      title: "数据处理",
      count: exampleRoutes.filter(categoryFilters["数据处理"]).length,
    },
  ];

  // 过滤示例 - 同时应用搜索和分类过滤
  useEffect(() => {
    // 应用分类过滤器
    const categoryFilter =
      categoryFilters[selectedCategory as keyof typeof categoryFilters] ||
      categoryFilters["所有示例"];

    let filtered = exampleRoutes.filter(categoryFilter);

    // 应用搜索过滤
    if (searchText.trim()) {
      const term = searchText.toLowerCase();
      filtered = filtered.filter((example) => {
        const title = String(example.meta?.title || "").toLowerCase();
        const path = String(example.path).toLowerCase();
        return title.includes(term) || path.includes(term);
      });
    }

    setFilteredExamples(filtered);
  }, [searchText, selectedCategory]);

  // 处理分类点击事件
  const handleCategoryClick = (category: string) => {
    setSelectedCategory(category);
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Title level={2}>组件与示例库</Title>
        <Paragraph>
          以下是系统中所有可用的示例组件和演示页面，点击卡片可查看详情。
        </Paragraph>
      </div>

      <div className={styles.toolbar}>
        <div className={styles.categories}>
          <Space size={12}>
            {categories.map((cat) => (
              <Tag
                key={cat.title}
                color={cat.title === selectedCategory ? "blue" : undefined}
                className={styles.categoryTag}
                onClick={() => handleCategoryClick(cat.title)}
              >
                {cat.title} ({cat.count})
              </Tag>
            ))}
          </Space>
        </div>

        <Input
          placeholder="搜索示例..."
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          allowClear
          className={styles.searchInput}
        />
      </div>

      {filteredExamples.length === 0 ? (
        <div className={styles.noResults}>
          <Icon name="NoApp" size={64} />
          <Paragraph>
            {searchText
              ? "没有找到匹配的示例"
              : `${selectedCategory}分类下暂无示例`}
          </Paragraph>
          <Button
            type="primary"
            onClick={() => {
              setSearchText("");
              setSelectedCategory("所有示例");
            }}
          >
            查看全部示例
          </Button>
        </div>
      ) : (
        <Row gutter={[16, 16]} className={styles.exampleGrid}>
          {filteredExamples.map((example) => (
            <Col xs={24} sm={12} md={8} lg={6} key={example.path}>
              <ExampleCard
                example={example}
                onClick={() => navigate(`/${example.path}`)}
              />
            </Col>
          ))}
        </Row>
      )}
    </div>
  );
};

export default ExampleIndex;
